﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

namespace BHair.Report
{
    public partial class Frmcishufenxi : WeifenLuo.WinFormsUI.Docking.DockContent
    {
        public Frmcishufenxi()
        {
            InitializeComponent();
        }
        string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
        private void button1_Click(object sender, EventArgs e)
        {
            /* string sql = string.Format("SELECT distinct [cardid] as 卡号,member.mname as 姓名,sum([xfcs]) as 次数 FROM [jcxf] left join member on jcxf.cardid=member.mid where riqi>=convert(datetime,'{0} 00:00:00',120) and riqi<=convert(datetime,'{1} 23:59:59',120) group by cardid,member.mname order by cardid ", dateTimePicker1.Text,dateTimePicker2.Text);
             SqlConnection conn = new SqlConnection(constr);
             conn.Open();
             SqlDataAdapter sda = new SqlDataAdapter(sql,conn);
             DataTable dt = new DataTable();
             sda.Fill(dt);
             dataGridView1.DataSource = dt;
             conn.Close();
             */
            fenxi();
        }
        public void fenxi()
        {
            //建立datetable
            DataTable dt = new DataTable();
            //创建列
            dt.Columns.Add("卡号", typeof(string));
            dt.Columns.Add("姓名", typeof(String));
            dt.Columns.Add("消费次数", typeof(String));
           
            SqlConnection conn = new SqlConnection(constr);
            SqlConnection conn1 = new SqlConnection(constr);
            conn.Open();
            conn1.Open();
            object obj1;
            decimal mincs;
            //查找消费卡号
            string sql =string.Format("SELECT distinct [cardid],member.mname  FROM [jcxf] inner join member on jcxf.cardid=member.mid  where riqi>= convert(datetime,'{0} 00:00:00',120) and riqi<=convert(datetime,'{1} 23:59:59',120)", dateTimePicker1.Text,dateTimePicker2.Text);
            SqlCommand comm = new SqlCommand(sql,conn);
            SqlDataReader sdr = comm.ExecuteReader();
            while (sdr.Read())
            {
                DataRow dr = dt.NewRow();
                dr["卡号"] = sdr["cardid"].ToString();
                dr["姓名"] = sdr["mname"].ToString();
                //查询消费次数并赋值
                string sql1 = string.Format("select SUM(xfcs) from jcxf where cardid='{0}' and riqi>= convert(datetime,'{1} 00:00:00',120) and riqi<=convert(datetime,'{2} 23:59:59',120)", sdr["cardid"].ToString(),dateTimePicker1.Text,dateTimePicker2.Text);
                SqlCommand comm1 = new SqlCommand(sql1, conn1);
                obj1 = comm1.ExecuteScalar();
                try
                {
                    if (obj1 != null)
                    {
                        mincs = decimal.Parse(comm1.ExecuteScalar().ToString());
                    }
                    else
                    {
                        mincs = decimal.Parse("0.00");
                    }
                }
                catch { mincs = decimal.Parse("0.00"); }
                dr["消费次数"] = mincs;
               
                dt.Rows.Add(dr);
            }
            dataGridView1.DataSource = dt;
            conn.Close();
        }


        private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出Excel文件到";

            saveFileDialog.ShowDialog();

            // 这个一定要加上，要不然，点取消按钮就会提示“索引超出了数组界限”的错误。
            //用saveFileDialog.ShowDialog() == DialogResult.Cancle 不管用，会出现2次存储窗口。
            if (saveFileDialog.FileName == "")
            {

                return;
            }


            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string str = "";
            try
            {
                //写标题       
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += dataGridView1.Columns[i].HeaderText;
                }
                sw.WriteLine(str);
                //写内容    
                for (int j = 0; j < dataGridView1.Rows.Count; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < dataGridView1.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }
                        if (dataGridView1.Rows[j].Cells[k].Value != null)
                        {

                            tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
                        }
                        else
                        {
                            tempStr += "";
                        }
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
                MessageBox.Show("导出成功");
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
       e.RowBounds.Location.Y,
       dataGridView1.RowHeadersWidth - 4,
       e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
            dataGridView1.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
    }
}
